package com.darwin.darwinNet
{
	import com.darwin.darwinNet.events.NetErrorEvent;
	import com.darwin.darwinNet.events.NetEvent;
	
	import flash.events.EventDispatcher;
	import flash.events.NetStatusEvent;
	import flash.net.NetConnection;
	import flash.net.Responder;
	
	
	/**
	 * AMF通讯类
	 * @author DOM
	 */	
	public class FAmf extends EventDispatcher
	{
		public function FAmf()
		{
			super();
		}
		/**
		 * 连接对象 
		 */		
		private var amfConnection:NetConnection;
		/**
		 * 调用的类加方法名 
		 */		
		private var callMethod:String = "";
		
		/**
		 * 进行AMF连接
		 * @param endpoint 服务器端入口地址
		 * @param source 要连接的对象名称
		 * @param method 要调用对象的方法名
		 * @param destination 可选，服务的目标。该值应与 services-config.xml 文件中的目标条目匹配。
		 */		
		public function connectAmf(endpoint:String,source:String,method:String):void
		{
			this.callMethod = source+"/"+method;
			amfConnection = new NetConnection();
			amfConnection.addEventListener(NetStatusEvent.NET_STATUS,onNetStatus);
			amfConnection.connect(endpoint);			
			if(delaySend.length>0)
			{
				if(callMethod==null||callMethod=="")
					return;
				for each(var data:Object in delaySend)
					amfConnection[callMethod](data);
				delaySend = [];
			}
		}
		/**
		 * 初始连接错误
		 */		
		protected function onNetStatus(event:NetStatusEvent):void
		{
			if(event.info.level=="error")
			{
				var ioErrorEvent:NetErrorEvent = new NetErrorEvent(NetErrorEvent.NET_IOERROR);
				dispatchEvent(ioErrorEvent);
			}
		}
		/**
		 * 网络请求发生错误
		 */		
		protected function onFault(status:Object):void
		{
			var ioErrorEvent:NetErrorEvent = new NetErrorEvent(NetErrorEvent.NET_IOERROR);
			dispatchEvent(ioErrorEvent);
		}
		/**
		 * 请求数据返回
		 */		
		protected function onResult(result:Object):void
		{
			var completeEvent:NetEvent = new NetEvent(NetEvent.NET_COMPLETE,result);
			dispatchEvent(completeEvent);
		}
		/**
		 * 还未连接前缓存的发送数据队列 
		 */		
		private var delaySend:Array = [];
		
		/**
		 * 发送网络请求 
		 * @param cmd 命令方法名
		 * @param data 要发送的数据对象
		 */		
		public function send(data:Object):void
		{
			if(amfConnection==null)
			{
				delaySend.push(data);
				return;
			}
			if(callMethod==null||callMethod=="")
				return;
			amfConnection.call(callMethod, new Responder(onResult,onFault),data);
		}
	}
}